package es.deusto.eside.programacion4.mario2d.states;

import es.deusto.eside.programacion4.mario2d.Mario2D;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.Music;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import TWLSlick.TWLInputAdapter;
import de.matthiasmann.twl.Button;
import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.Widget;
import de.matthiasmann.twl.renderer.lwjgl.LWJGLRenderer;
import de.matthiasmann.twl.theme.ThemeManager;



public class OptionStage extends BasicGameState {
	/**
	 * boton de aceptar
	 */
	private Button accept;

	/**
	 * boton de cancelar
	 */
	private Button cancel;

	/**
	 * Fuente
	 */
	private UnicodeFont fpsFont;

	/**
	 * stateId: indica el estado del programa
	 */
	private int stateId;

	/**
	 * Widget padre
	 */
	private Widget root;

	/**
	 * LWGLRenderer contexto de renderizado
	 */
	private LWJGLRenderer lwjglRenderer;
	/**
	 * theme tema usado para la escritura
	 */
	private Object theme;

	/**
	 * gui intefaz de usuario
	 */
	private GUI gui;
	/**
	 * twlInputoAdapter: gestiona las entradas de los botones
	 */
	private TWLInputAdapter twlInputAdapter;

	/**
	 * Ruta del estilo
	 */
	private static final String fontPath = "resources/ttf/mario.ttf";

	/**
	 * Imagen de fondo
	 */
	Image background;

	/**
	 * Imagen aceptado
	 */
	Image check;

	/**
	 * Imagen cancelado
	 */
	Image uncheck;

	/**
	 * Cancion
	 */
	Music song;

	/**
	 * String para el full screen
	 */
	private String isF;

	/**
	 * String para e volumen
	 */
	private String isV;
	
	/**
	 * Para leer el fichero solo la primera vez
	 */
	private int p = 0;

	/**
	 * Constructor
	 * 
	 * @param ordinal
	 *            : número de estado del programa
	 */
	public OptionStage(int ordinal) {
		this.stateId = ordinal;
	}

	@Override
	public void enter(final GameContainer gameContainer, final StateBasedGame sb) {
		gameContainer.getInput().addPrimaryListener(twlInputAdapter);
		if (Mario2D.p.isMusic() == true) {
			Mario2D.option.loop();
		}

	}

	@Override
	public void leave(final GameContainer gameContainer, final StateBasedGame sb) {
		gameContainer.getInput().removeListener(twlInputAdapter);
		Mario2D.option.stop();
	}

	@Override
	public void init(GameContainer gameContainer, StateBasedGame sb)
			throws SlickException {
		/* song = new Music("resources/Music/Option.ogg"); */
		check = new Image("resources/Images/Option/checkbox_checked.png");
		uncheck = new Image("resources/Images/Option/checkbox_unchecked.png");
		check = check.getScaledCopy(50, 50);
		uncheck = uncheck.getScaledCopy(50, 50);
		background = new Image("resources/Images/Option/option.jpg");
		background = background.getScaledCopy(Mario2D.WIDTH, Mario2D.HEIGHT);
		initGUI(gameContainer, sb);
		fpsFont = new UnicodeFont(fontPath, 40, true, false);
		fpsFont.addAsciiGlyphs();
		fpsFont.addGlyphs(400, 600);
		fpsFont.getEffects().add(new ColorEffect(java.awt.Color.WHITE));
		fpsFont.loadGlyphs();
	}

	/**
	 * 
	 * @param gc
	 *            : ventana del juego
	 * @param sb
	 *            : lleva el control de los estados del juego
	 */
	private void initGUI(final GameContainer gc, final StateBasedGame sb) {
		initTWL(gc);
		twlInputAdapter = new TWLInputAdapter(gui, gc.getInput());

		createButtons();
		initButtonsEvent(sb);
	}

	/**
	 * Inicia los eventos de botones
	 * 
	 * @param sb
	 *            estado del juego
	 */
	private void initButtonsEvent(final StateBasedGame sb) {
		cancel.addCallback(new Runnable() {

			@Override
			public void run() {
				//Restaurar los valores iniciales de isF e isV
				if(Mario2D.p.isFullScreen() == false)
					isF = "activatedFullScreen: false";
				else
					isF = "activatedFullScreen: true";
				if(Mario2D.p.isMusic() == false)
					isV = "activatedVolume: false";
				else
					isV = "activatedVolume: true";
				sb.enterState(GameState.MENU_STATE.ordinal());
		}
	});
		accept.addCallback(new Runnable() {

			@Override
			public void run() {
				// Create file
				FileWriter fstream;
				try {
					fstream = new FileWriter("resources/Option/option.txt");
					BufferedWriter out = new BufferedWriter(fstream);
					if (isF.equals("activatedFullScreen: true")) {
						Mario2D.p.setFullScreen(true);
						System.out.println(isF);
						out.write(isF);
						out.newLine();
					} else {
						Mario2D.p.setFullScreen(false);
						System.out.println(isF);
						out.write(isF);
						out.newLine();
					}
					if (isV.equals("activatedVolume: true")) {
						Mario2D.p.setMusic(true);
						System.out.println(isV);
						out.write(isV);
						out.newLine();
					} else {
						Mario2D.p.setMusic(false);
						System.out.println(isV);
						out.write(isV);
						out.newLine();
					}
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				sb.enterState(GameState.MENU_STATE.ordinal());
			}
		});
	}

	/**
	 * Crea los botones
	 */
	private void createButtons() {
		accept = new Button();
		accept.setText("Accept");
		accept.setTheme("button");
		accept.setPosition(50, 400);
		twlInputAdapter.getGui().getRootPane()
				.setSize(Mario2D.WIDTH, Mario2D.HEIGHT);
		twlInputAdapter.getGui().getRootPane().add(accept);
		accept.adjustSize();

		cancel = new Button();
		cancel.setText("Cancel");
		cancel.setTheme("button");
		cancel.setPosition(400, 400);

		twlInputAdapter.getGui().getRootPane()
				.setSize(Mario2D.WIDTH, Mario2D.HEIGHT);
		twlInputAdapter.getGui().getRootPane().add(cancel);
		cancel.adjustSize();
	}

	/**
	 * Inicializa el tema de escritura
	 * 
	 * @param gc
	 *            : ventana del juego
	 */
	private void initTWL(GameContainer gc) {
		root = new Widget();
		root.setTheme("");

		// save Slick's GL state while loading the theme
		GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
		try {
			lwjglRenderer = new LWJGLRenderer();
			theme = ThemeManager.createThemeManager(new URL(
					"file:resources/theme/LuffySurvivalTheme.xml"),
					lwjglRenderer);

			gui = new GUI(root, lwjglRenderer);
			gui.applyTheme((ThemeManager) theme);
		} catch (LWJGLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// restore Slick's GL state
			GL11.glPopAttrib();
		}

	}

	@Override
	public void render(GameContainer arg0, StateBasedGame sb, Graphics g)
			throws SlickException {
		org.newdawn.slick.Color black = new org.newdawn.slick.Color(0, 0, 0,
				200);
		org.newdawn.slick.Color white = new org.newdawn.slick.Color(255, 255,
				255, 255);
		// Rect r1 = new Rect(3, Mario2D.HEIGHT-71 , 5, 5);
		// Rect r2 = new Rect(Mario2D.WIDTH-71, 3 , 5, 5);

		Rectangle rect = new Rectangle(38, 38, Mario2D.WIDTH - 76,
				Mario2D.HEIGHT - 76);
		// g.setFont(theme);

		if(p==0){
			//leer el fichero de options solo una vez
			try {
				// Open the file that is the first
				// command line parameter
				FileInputStream fstream = new FileInputStream(
						"resources/Option/option.txt");
				// Get the object of DataInputStream
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(in));
				isF = br.readLine();
				System.out.println(isF);
				isV = br.readLine();
				System.out.println(isV);
				// Close the input stream
				in.close();
				System.out.println(p);
				if (isF.equals("activatedFullScreen: true")){
					Mario2D.p.setFullScreen(true);
				}
				else {
					Mario2D.p.setFullScreen(false);
				}

				if (isV.equals("activatedVolume: true")){
					Mario2D.p.setMusic(true);
				}
				else {
					 Mario2D.p.setMusic(false);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(p<2)
			p++;
		
		g.drawImage(background, 0, 0);
		g.setColor(white);
		g.fillRect(33, 33, 5, Mario2D.HEIGHT - 71);
		g.fillRect(Mario2D.WIDTH - 38, 38, 5, Mario2D.HEIGHT - 76);
		g.fillRect(33, 33, Mario2D.WIDTH - 66, 5);
		g.fillRect(33, Mario2D.HEIGHT - 38, Mario2D.WIDTH - 66, 5);
		g.setColor(black);
		g.fill(rect);
		Image title = new Image("resources/Images/Option/title.png");
		g.drawImage(title, Mario2D.WIDTH / 2 - title.getWidth() / 2, 0);
		// g.drawString(Locale.INSTANCE.getText("Option"), 280, 30);
		fpsFont.drawString(250, 15, "Option");
		// 80, 193
		g.setColor(white);
		
		fpsFont.drawString(80, 193, ("fullScreen"));
		if (isF.equals("activatedFullScreen: false")) {
			g.drawImage(uncheck, 365, 193);
		} else {
			g.drawImage(check, 365, 193);
		}
		fpsFont.drawString(80, 293, "Volume");
		if (isV.equals("activatedVolume: true")) {
			g.drawImage(check, 270, 293);
		} else {
			g.drawImage(uncheck, 270, 293);
		}
		twlInputAdapter.render();
	}

	@Override
	public void update(GameContainer gc, StateBasedGame arg1, int arg2)
			throws SlickException {
		Input input = gc.getInput();
		int positionX = input.getMouseX();
		int positionY = input.getMouseY();
		if (positionX > 365 && positionX < 415 && positionY > 193
				&& positionY < 243
				&& input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
				if(isF.equals("activatedFullScreen: true"))
					isF = "activatedFullScreen: false";
				else
					isF = "activatedFullScreen: true";
		}
		if (positionX > 270 && positionX < 320 && positionY > 293
				&& positionY < 343
				&& input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
			if(isV.equals("activatedVolume: true"))
				isV = "activatedVolume: false";
			else
				isV = "activatedVolume: true";
		}
	}

	@Override
	public int getID() {
		return this.stateId;
	}

}
